<?php
/* This file is part of Mirasol CMS
   (C) 2011-2012 by Chris Alban Hansen.
   Released under the terms of the GNU General Public License.
   See COPYING in the top level directory of the Mirasol CMS installation. */

include "{$_SERVER['DOCUMENT_ROOT']}/includes/config.php";
include "{$_SERVER['DOCUMENT_ROOT']}/includes/core.php";
include "{$_SERVER['DOCUMENT_ROOT']}/includes/db.php";
include "{$_SERVER['DOCUMENT_ROOT']}/includes/largetext.php";
include "{$_SERVER['DOCUMENT_ROOT']}/includes/login.php";

if ($login['username'] == "")
{
  header ("location: ./");
  exit;
}

$connection = db_open ();

/* Create the XML feed */
if (isset ($_POST['pid']))
{
  $version = $_POST['pagever'];
  
  if (!isset ($_POST['approve']) && !isset ($_POST['revert']))
    {
      $path = isset ($_POST['path']) ? $_POST['path'] : "";
      $path = str_replace (" ", "_", $path);
      while (substr ($path, 0, 1) == "/")
        $path = substr ($path, 1);
        
      $title = htmlentities (trim ($_POST['title']), ENT_COMPAT, "UTF-8", false);
      $title = htmlentities ($title, ENT_COMPAT, "UTF-8", true);
      
      $xmlfeed = "<page><title>$title</title><fields>";
      
      $tbl_pages = db_maketablename ($table_pages_review);
      $tbl_templates = db_maketablename ($table_templates);
      $result = mysql_query ("SELECT $tbl_templates.fields FROM $tbl_pages LEFT JOIN $tbl_templates ON $tbl_templates.id=$tbl_pages.template WHERE $tbl_pages.id='{$_POST['pid']}'");
      if (mysql_num_rows ($result) > 0)
        {
          $row = mysql_fetch_array ($result);
          
          /* Prepare the XML parser and parse the data */
          $xmldata = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n".$row['fields'];     
          $xmlres = xml_parser_create ("utf-8");
          xml_parse_into_struct ($xmlres, $xmldata, $values);
          xml_parser_free ($xmlres);
          
          /* Walk through the tags */
          $i = 0;
          while (!empty ($values[$i]))
            {
              if ($values[$i]['level'] == 2 && strcasecmp ($values[$i]['tag'], "field") == 0 && isset ($values[$i]['attributes']['NAME']) && isset ($values[$i]['attributes']['TYPE']))
                {
                  $name = $values[$i]['attributes']['NAME'];
                  $value = trim ($_POST[$name]);
                  
                  /* Format 'largetext' fields */
                  if ($values[$i]['attributes']['TYPE'] == "largetext")
                    {
                      $value = htmlentities ($value, ENT_COMPAT, "UTF-8", false);
                      $value = nl2br ($value);
                      $value = str_replace ("\r", "", $value);
                      $value = str_replace ("\n", "", $value);
                      $value = largetext_format ($value);
                    }
                  
                  /* Format 'text' fields */
                  if ($values[$i]['attributes']['TYPE'] == "text")
                    $value = htmlentities ($value, ENT_COMPAT, "UTF-8", false);
                    
                  $value = htmlentities ($value, ENT_COMPAT, "UTF-8", true);
                  $value = encodehtml ($value);
                  $xmlfeed .= "<$name>$value</$name>";
                }
              $i++;
            }
        }
      mysql_free_result ($result);
    
      $xmlfeed .= "</fields></page>";
      
      /* Now update the page in the database */
      if ($path != "")
        {
          /* If the path has changed, we must change the path on every version of the page */
          $result = mysql_query ("SELECT path FROM ".db_maketablename ($table_pages_review)." WHERE id='{$_POST['pid']}'");
          if (mysql_num_rows ($result) > 0)
            {
              $row = mysql_fetch_array ($result);
              $origpath = $row['path'];
            }
          mysql_free_result ($result);
          
          if ($origpath != $path)
            {
              $result = mysql_query ("SELECT id FROM ".db_maketablename ($table_pages_review)." WHERE guid='{$_POST['guid']}'");
              if (mysql_num_rows ($result) > 0)
                {
                  while ($row = mysql_fetch_array ($result))
                    mysql_query ("UPDATE ".db_maketablename ($table_pages_review)." SET path='".mysql_real_escape_string ($path)."' WHERE id='{$row['id']}'");
                }
              mysql_free_result ($result);
            }
        }
      
      /* Update start time */
      if (isset ($_POST['startnow']) && $_POST['startnow'] == "on")
        $starttime = time ();
      if (isset ($_POST['endnow']) && $_POST['endnow'] == "on" && !isset ($starttime))
        $starttime = 0;
      if (!isset ($starttime))
        {
          if (!ini_get ('date.timezone'))
            date_default_timezone_set ("UTC");
          $date = explode ("/", $_POST['startdate']);
          $ampm = $_POST['startpm'] == 1 ? "pm" : "am";
          $time24 = date ("H:i", strtotime ("{$_POST['starttime']} $ampm"));
          $time = explode (":", $time24);
          if (count ($date) == 3 && count ($time) == 2)
            {
              if ($date[0] > 0 && $date[0] < 13 && $date[1] > 0 && $date[1] < 32 && $date[2] >= idate ("Y", time ()) && checkdate ($date[0], $date[1], $date[2]) && $time[0] >= 0 && $time[0] <= 23 && $time[1] >= 0 && $time[1] <= 59)
                $starttime = mktime ($time[0], $time[1], 0, $date[0], $date[1], $date[2]);
            }
        }
      if (isset ($starttime))
        mysql_query ("UPDATE ".db_maketablename ($table_pages_review)." SET starttime='$starttime' WHERE id='{$_POST['pid']}'");

      /* Update end time */
      if (isset ($_POST['endnow']) && $_POST['endnow'] == "on")
        $endtime = time ();
      if (isset ($_POST['noenddate']) && $_POST['noenddate'] == "on" && !isset ($endtime))
        $endtime = 0;
      if (!isset ($endtime))
        {
          date_default_timezone_set ("UTC");
          $date = explode ("/", $_POST['enddate']);
          $ampm = $_POST['endpm'] == 1 ? "pm" : "am";
          $time24 = date ("H:i", strtotime ("{$_POST['endtime']} $ampm"));
          $time = explode (":", $time24);
          if (count ($date) == 3 && count ($time) == 2)
            {
              if ($date[0] > 0 && $date[0] < 13 && $date[1] > 0 && $date[1] < 32 && $date[2] >= idate ("Y", time ()) && checkdate ($date[0], $date[1], $date[2]) && $time[0] >= 0 && $time[0] <= 23 && $time[1] >= 0 && $time[1] <= 59)
                $endtime = mktime ($time[0], $time[1], 0, $date[0], $date[1], $date[2]);
            }
        }
      if (isset ($endtime) && ($endtime >= $starttime || $endtime == 0))
        mysql_query ("UPDATE ".db_maketablename ($table_pages_review)." SET endtime='$endtime' WHERE id='{$_POST['pid']}'");

      /* Finally update the current page */
      $now = time ();
      mysql_query ("UPDATE ".db_maketablename ($table_pages_review)." SET template='{$_POST['template']}', xmlfeed='".mysql_real_escape_string ($xmlfeed)."', lastedit='$now' WHERE id='{$_POST['pid']}'");
      
      /* New version? */
      if (isset ($_POST['addversion']))
        {
          /* Fetch the highest version number of the page */
          $newversion = $version;
          $result = mysql_query ("SELECT version FROM ".db_maketablename ($table_pages_review)." WHERE guid='{$_POST['guid']}' ORDER BY version DESC");
          if (mysql_num_rows ($result) > 0)
            {
              $row = mysql_fetch_array ($result);
              $version = $row['version'];
            }
          mysql_free_result ($result);
          
          /* Add one to the version number */
          $version++;
          
          /* Copy the page to a new row with the upgraded version number */
          mysql_query ("INSERT INTO ".db_maketablename ($table_pages_review)." (path, version, template, xmlfeed, guid, lastedit) SELECT path, '$version', template, xmlfeed, guid, lastedit FROM ".db_maketablename ($table_pages_review)." WHERE id='{$_POST['pid']}'");
        }
    }
  else if (isset ($_POST['approve']))
    {
      $tbl_pages = db_maketablename ($table_pages);
      $tbl_pages_review = db_maketablename ($table_pages_review);
      
      /* If the path has changed, we must change the path on every version of the page */
      $result = mysql_query ("SELECT path FROM $tbl_pages WHERE guid='{$_POST['guid']}' LIMIT 1");
      if (mysql_num_rows ($result) > 0)
        {
          $row = mysql_fetch_array ($result);
          $origpath = $row['path'];
        }
      mysql_free_result ($result);

      $result = mysql_query ("SELECT path FROM $tbl_pages_review WHERE guid='{$_POST['guid']}' LIMIT 1");
      if (mysql_num_rows ($result) > 0)
        {
          $row = mysql_fetch_array ($result);
          $path = $row['path'];
        }
      mysql_free_result ($result);
          
      if ($origpath != $path)
        {
          $result = mysql_query ("SELECT id FROM $tbl_pages WHERE guid='{$_POST['guid']}'");
          if (mysql_num_rows ($result) > 0)
            {
              while ($row = mysql_fetch_array ($result))
                mysql_query ("UPDATE $tbl_pages SET path='".mysql_real_escape_string ($path)."' WHERE id='{$row['id']}'");
            }
          mysql_free_result ($result);
        }
      
      /* Finally approve the changes */
      $result = mysql_query ("SELECT id FROM $tbl_pages WHERE version='$version' AND guid='{$_POST['guid']}'");
      if (mysql_num_rows ($result) == 0)
        mysql_query ("INSERT INTO $tbl_pages (path, version, starttime, endtime, template, xmlfeed, guid, lastedit) SELECT path, version, starttime, endtime, template, xmlfeed, guid, lastedit FROM $tbl_pages_review WHERE version='$version' AND guid='{$_POST['guid']}'");
      else
        mysql_query ("UPDATE $tbl_pages, $tbl_pages_review SET $tbl_pages.path=$tbl_pages_review.path, $tbl_pages.starttime=$tbl_pages_review.starttime, $tbl_pages.endtime=$tbl_pages_review.endtime, $tbl_pages.template=$tbl_pages_review.template, $tbl_pages.xmlfeed=$tbl_pages_review.xmlfeed, $tbl_pages.lastedit=$tbl_pages_review.lastedit WHERE $tbl_pages.version='$version' AND $tbl_pages.guid='{$_POST['guid']}' AND  $tbl_pages_review.version='$version' AND $tbl_pages_review.guid='{$_POST['guid']}'");
      mysql_free_result ($result);
    }
  else if (isset ($_POST['revert']))
    {
      $tbl_pages = db_maketablename ($table_pages);
      $tbl_pages_review = db_maketablename ($table_pages_review);
      
      /* If the path has changed, we must change the path on every version of the page */
      $result = mysql_query ("SELECT path FROM $tbl_pages WHERE guid='{$_POST['guid']}' LIMIT 1");
      if (mysql_num_rows ($result) > 0)
        {
          $row = mysql_fetch_array ($result);
          $origpath = $row['path'];
        }
      mysql_free_result ($result);

      $result = mysql_query ("SELECT path FROM $tbl_pages_review WHERE guid='{$_POST['guid']}' LIMIT 1");
      if (mysql_num_rows ($result) > 0)
        {
          $row = mysql_fetch_array ($result);
          $path = $row['path'];
        }
      mysql_free_result ($result);
          
      if ($origpath != $path)
        {
          $result = mysql_query ("SELECT id FROM $tbl_pages_review WHERE guid='{$_POST['guid']}'");
          if (mysql_num_rows ($result) > 0)
            {
              while ($row = mysql_fetch_array ($result))
                mysql_query ("UPDATE $tbl_pages_review SET path='".mysql_real_escape_string ($path)."' WHERE id='{$row['id']}'");
            }
          mysql_free_result ($result);
        }

      /* Finally approve the changes */
      $result = mysql_query ("SELECT id FROM $tbl_pages_review WHERE version='$version' AND guid='{$_POST['guid']}'");
      if (mysql_num_rows ($result) == 0)
        mysql_query ("INSERT INTO $tbl_pages_review (path, version, starttime, endtime, template, xmlfeed, guid, lastedit) SELECT path, version, starttime, endtime, template, xmlfeed, guid, lastedit FROM $tbl_pages WHERE version='$version' AND guid='{$_POST['guid']}'");
      else {
        mysql_query ("UPDATE $tbl_pages_review, $tbl_pages SET $tbl_pages_review.path=$tbl_pages.path, $tbl_pages_review.starttime=$tbl_pages.starttime, $tbl_pages_review.endtime=$tbl_pages.endtime, $tbl_pages_review.template=$tbl_pages.template, $tbl_pages_review.xmlfeed=$tbl_pages.xmlfeed, $tbl_pages_review.lastedit=$tbl_pages.lastedit WHERE $tbl_pages.version='$version' AND $tbl_pages.guid='{$_POST['guid']}' AND $tbl_pages_review.version='$version' AND $tbl_pages_review.guid='{$_POST['guid']}'");
      }
      mysql_free_result ($result);
    }
}

db_close ($connection);
header ("location:$app_adminpath/?p=pages&guid={$_POST['guid']}&ver=$version&show={$_POST['show']}");
exit;
?>
